package com.qf.test;

import com.qf.util.ZkUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.List;

public class Demo {

    @Test
    public void getChildren() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        // ls命令
        List<String> znodeList = cf.getChildren().forPath("/zookeeper");

        for (String s : znodeList) {
            System.out.println(s);
        }
    }

    @Test
    public void getData() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        byte[] bytes = cf.getData().forPath("/xx");

        System.out.println(new String(bytes));
    }



    @Test
    public void create() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        String s = cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/xx/zz", "嘿嘿嘿".getBytes());

        System.out.println(s);
    }

    @Test
    public void setData() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        Stat stat = cf.setData().forPath("/zz", "嘻嘻嘻".getBytes());

        System.out.println(stat);
    }


    @Test
    public void delete() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        cf.delete().deletingChildrenIfNeeded().forPath("/xx");
    }

    @Test
    public void checkExists() throws Exception {
        CuratorFramework cf = ZkUtil.getConn();

        Stat stat = cf.checkExists().forPath("/zz");

        System.out.println(stat);
    }

    @Test
    public void listenZnode() throws Exception {
        // 设置连接对象,并且指定监听/zz的节点
        NodeCache nodeCache = new NodeCache(ZkUtil.getConn(),"/zz");

        // 给nodeCache添加监听器
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点名称:" + nodeCache.getCurrentData().getPath());
                System.out.println("节点数据:" + new String(nodeCache.getCurrentData().getData()));
                System.out.println("节点信息:" + nodeCache.getCurrentData().getStat());
            }
        });

        // 开始监听
        nodeCache.start();

        System.out.println("开始监听!!!");
        System.in.read();
    }



















}